/**
 *
 */
package com.py.credit.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.enums.BasicTableFieldEnum;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.ShareLogService;
import com.py.credit.service.ZwcxContentService;
import com.py.credit.service.ZwcxSearchService;
import com.py.credit.utils.NumberUtils;
import com.py.credit.utils.elasticsearch.EsPage;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * @author zhuzh
 *
 */
@RestController
@RequestMapping(value = "/zwcxsearch")
public class ZwcxSearchController {

    private final static String FRONT_TABLE_ID = "zwcxsearch";
    
    @Autowired
    private ZwcxSearchService zwcxSearchService;
    
    @Autowired
    private RemoteBaseService remoteBaseService;

    @Autowired
    private ShareLogService shareLogService;
    
    @Autowired
    private ZwcxContentService zwcxContentService;
    
    @Value("${useEs}")
    private boolean useEs;
    
    
    
    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page) {

        List<String> showColumns = BasicTableFieldEnum.getDefaultShowColumnEN(kId);

        String[] additionalColumns = {"tybm"};

        List<Map<String, Object>> tableList = zwcxSearchService.getByConditionForPage(kId, showColumns, additionalColumns,
                condition, page);

        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }
    
    
    
    @RequestMapping(value = "/getHistoryList.json")
    public RestServiceResult<List<Map<String, Object>>> getHistoryList(HttpServletRequest request,
                                                                       @RequestParam(value = "kId") String kId) {

        long userId = 0L;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userId = userInfo.getId();

            } else {

                ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
        }

        List<Map<String, Object>> historyLsit = zwcxSearchService.getSharingSearchHistoryList(userId, kId);

        List<Map<String, Object>> uniqueList = new ArrayList<Map<String, Object>>(historyLsit.size());

        for (Map<String, Object> map : historyLsit) {

            Map<String, Object> singleReocrd = zwcxSearchService.getUniqueList(map);

            if ("100001".equals(kId) && !CollectionUtils.isEmpty(singleReocrd)) {

                String idEncrypt = NumberUtils.idEncrypt((String) singleReocrd.get("B000002"));
                singleReocrd.put("B000002", idEncrypt);

            }

            if (singleReocrd != null) {

                uniqueList.add(singleReocrd);

            }

        }
        return new RestServiceResult<List<Map<String, Object>>>(uniqueList);
    }
    
    
    @IgnoreAuthority
    @RequestMapping(value = "/getSubjectList.json")
    public RestServiceResult<List<Map<String, String>>> getSubjectLsit(@RequestParam(value = "kId") String kId,
                                                                       @RequestParam(value = "input") String input, Page page, EsPage esPage) {

        List<Map<String, String>> keyWords = null;

        int total = 0;

        if (StringUtils.isNotBlank(input)) {

            if (useEs) {

                keyWords = zwcxSearchService.getKeyWordsByEs(kId, input, esPage);

                total = esPage.getTotalCount();

            } else {

                keyWords = zwcxSearchService.getSubjectLsitForPage(kId, input, page);

                total = page.getTotalCount();
            }

        }
        return new RestServiceResult<List<Map<String, String>>>(total,
                keyWords == null ? new ArrayList<Map<String, String>>() : keyWords);

    }
    
    
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getDetail.json")
    public RestServiceResult<Object> getDetail(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "keyWord", defaultValue = "", required = true) String keyWord,
            HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        String username = "";
        String realName = "";
        long id = 0L;
        long deptId = 0;
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            userInfo = user.getData();

            if (null != userInfo) {

                username = userInfo.getUsername();

                realName = userInfo.getRealName();

                deptId = userInfo.getOfficeId();

                id = userInfo.getId();
            } else {

                ExceptionLogger.error("SsearchController#getDetail", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#getDetail", "未获取到当前用户信息！");
        }

        Map<String, Object> detail = zwcxContentService.getDetail(kId, tybm, "ZWCX", userInfo);

        zwcxSearchService.addHistory(tybm, kId, id);

        shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), username,
                realName, deptId, keyWord);
        // 根据样式展示
        List<TableResult> data = zwcxSearchService.assembleTableComponent((List<TableResult>) detail.get("results"));

        return new RestServiceResult<Object>(data);

    }
    
    @RequestMapping(value = "/getKeyWord.json")
    public RestServiceResult<List<Map<String, String>>> getKeyWord(@RequestParam(value = "kId") String kId,
                                                                   @RequestParam(value = "name") String input) {

        List<Map<String, String>> keyWords = null;

        if (StringUtils.isNotBlank(input)) {
            if (useEs) {
                keyWords = zwcxSearchService.getKeyWordsByEs(kId, input, new EsPage());
            } else {
                keyWords = zwcxSearchService.getKeyWords(kId, input);
            }
        }
        return new RestServiceResult<List<Map<String, String>>>(
                keyWords == null ? new ArrayList<Map<String, String>>() : keyWords);

    }
}
